package com.sjq.common.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sjq.common.dao.ApplicationSystemDao;
import com.sjq.common.dao.AuthorizedDao;
import com.sjq.common.entity.ApplicationSystem;
import com.sjq.common.entity.LoginAccount;
import com.sjq.common.entity.Menu;
import com.sjq.common.service.AuthorizedService;
import com.sjq.common.service.MenuManagerService;
import com.sjq.common.web.SessionHelper;

@Service
public class AuthorizedServiceImpl implements AuthorizedService {
	@Resource
	private AuthorizedDao authorizedDao;
	@Resource
	private MenuManagerService menuManagerService;
	@Resource
	private ApplicationSystemDao applicationSystemDao;
	
	@Override
	public String selectYSQ(String jsid) {
		List<Menu> reults=new ArrayList<Menu>();
		//查找所有系统id
		List<ApplicationSystem> allSystem=applicationSystemDao.findAll();
		if(allSystem.size()>0){
			for(int i=0;i<allSystem.size();i++){
				//创建根节点
				Menu rootMenu=new Menu();
				rootMenu.setMenuId(i+"");
				rootMenu.setParentMenuId("0");
				rootMenu.setMenuName(allSystem.get(i).getXtmc());
				rootMenu.setSystemId(allSystem.get(i).getXxzjbh());
				rootMenu.setOrderno(i+"");
				rootMenu.setNocheck("true");
				reults.add(rootMenu);
				
				
			}
		}else{
			throw new RuntimeException("未查找到系统信息!");
		}
		
		List<Menu> menuList=authorizedDao.getAuthorizedMenu(jsid);
		reults.addAll(menuList);
		
		String json = JSONArray.fromObject(reults).toString();
		return json;
	}
	
	@Override
	@Transactional
	public String saveAuthorized( String jsid, String nodes,HttpServletRequest request)  {
		Map<String,String> map = new HashMap<String, String>();
		JSONArray arr = JSONArray.fromObject(nodes);
		//删除角色下所有授权菜单
		authorizedDao.deleteAuthorized(jsid);
		
		//获取session
		SessionHelper sh = SessionHelper.create(request);
		LoginAccount la = sh.getAttribute("account", LoginAccount.class);
		if(la!=null){//如果session为空
			
			//新增授权
			int[] i = authorizedDao.saveAuthorized(arr, jsid,la.getUserName(),la.getUserDwbm());

			boolean check = true;
			
			for(int s:i){
				if(s==0){
					check=false;
				}
			}
			
			if(check){
				map.put("result", "success");
				map.put("msg", "保存成功!");
			}else{
				map.put("result", "error");
				map.put("msg", "保存失败!");
				
			}
		}else{
			map.put("result", "error");
			map.put("msg", "保存失败!请先登录!");
		}
		String json=JSONObject.fromObject(map).toString();
		return json;
	}
}
